﻿/*
 * 内存缓存
 * 基于.net4.0 ,引用System.Runtime.Caching，注意跟 httpcontext cache的区别
 */
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Text;

namespace STX.Lib.Caching.Providers
{
    public class MemoryCacheProvider:ICacheProvider
    {
        protected ObjectCache Cache
        {
            get
            {
                return MemoryCache.Default;
            }
        }

        public void Set(string key, object value)
        {
            if (value == null) return;
            Set(key, value, 30);
        }

        public void Set(string key, object value, int expiresSecond)
        {
            if (value == null) return;

            var policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(expiresSecond);
            Cache.Add(new CacheItem(key, value), policy);
        }

        public bool IsSet(string key)
        {
            return Cache.Contains(key);
        }

        public T Get<T>(string key)
        {
            if (!IsSet(key)) return default(T);
            return (T)Cache[key];
        }

        public void Remove(string key)
        {
            Cache.Remove(key);

        }
        public void Clear()
        {
            foreach (var item in Cache)
                Remove(item.Key);
        }
    }
}
